Cakephp

Single click login into Facebook use api with in PHP / CakePHP

Single click login into Facebook use api with in PHP / CakePHP


Single click login into Facebook use api with in PHP / CakePHP

We are going to login to our Cakephp 2 website (which does not use composer) with a Facebook api. We are going to update our Social user's table and our normal users table. Basically if a user exist we are going to update other wise add the user.

Our first table is:

CREATE TABLE IF NOT EXISTS `user_socials` (
  `id` int(11) NOT NULL,
  `oauth_provider` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `oauth_uid` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `link` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `picture` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `created` datetime NOT NULL,
  `modified` datetime NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Our users table is:

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL,
  `user_role_id` int(1) NOT NULL,
  `firstname` varchar(100) NOT NULL,
  `lastname` varchar(100) NOT NULL,
  `google_id` varchar(255) DEFAULT NULL,
  `facebook_id` varchar(255) DEFAULT NULL,
  `linkedin_id` varchar(255) DEFAULT NULL,
  `email` varchar(100) NOT NULL,
  `password` varchar(100) NOT NULL,
  `created` date NOT NULL,
  `modified` date NOT NULL
) ENGINE=MyISAM AUTO_INCREMENT=1334 DEFAULT CHARSET=latin1;

we have optained the facbook api files at https://github.com/Skillbooker/facebook_oauth

The facebook function

This facebook function has to go in your controller.

public function facebook() {

define("SITEURL", "http://www.skillbooker.com/");    
define("FACEBOOK_KEY", "0000000000000000");
//your facebook key
define("FACEBOOK_SECRET", "000000000000000");
//your facebook secret key
define("FACEBOOK_REROUTE", "social/facebook");

    
    if(!session_id()) {
        session_start();
    }
    
    require_once(APP . 'Vendor' . DS . 'facebooker' . DS . 'src' . DS . 'Facebook' . DS . 'autoload.php');

    $fb = new Facebook\Facebook([
        'app_id' => FACEBOOK_KEY,
        'app_secret' => FACEBOOK_SECRET,
        'default_graph_version' => 'v2.4',
      ]);

    $helper = $fb->getRedirectLoginHelper();

    $permissions = ['email']; // optional
        
    try {
        if (isset($_SESSION['token'])) {
            $accessToken = $_SESSION['token'];
        } else {
            $accessToken = $helper->getAccessToken();
        }
    } catch(Facebook\Exceptions\FacebookResponseException $e) {
        // When Graph returns an error
        $error = 'Graph returned an error: ' . $e->getMessage();
        $this->Session->setFlash($error,'error');
        exit;
    } catch(Facebook\Exceptions\FacebookSDKException $e) {
        // When validation fails or other local issues
        $error = 'Facebook SDK returned an error: ' . $e->getMessage();
        $this->Session->setFlash($error,'error');
        exit;
     }
     

    if (isset($accessToken)) {
        
        if (isset($_SESSION['token'])) {
            $fb->setDefaultAccessToken($_SESSION['token']);
        } else {
            // getting short-lived access token
            $_SESSION['token'] = (string) $accessToken;

            // OAuth 2.0 client handler
            $oAuth2Client = $fb->getOAuth2Client();

            // Exchanges a short-lived access token for a long-lived one
            $longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['token']);

            $_SESSION['token'] = (string) $longLivedAccessToken;

            // setting default access token to be used in script
            $fb->setDefaultAccessToken($_SESSION['token']);
        }

        // redirect the user back to the same page if it has "code" GET variable
        if (isset($_GET['code'])) {
            header('Location: ./');
        }

        // getting basic info about user
        try {
            $profile_request = $fb->get('/me?fields=name,first_name,last_name,email,link');
            $userProfile = $profile_request->getGraphNode()->asArray();
        } catch(Facebook\Exceptions\FacebookResponseException $e) {
            // When Graph returns an error
            $error = 'Graph returned an error: ' . $e->getMessage();
            $this->Session->setFlash($error,'error');
            session_destroy();
            // redirecting user back to app login page
            header("Location: ./");
            exit;
        } catch(Facebook\Exceptions\FacebookSDKException $e) {
            // When validation fails or other local issues
            $error = 'Facebook SDK returned an error: ' . $e->getMessage();
            $this->Session->setFlash($error,'error');
            exit;
        }
        
        // printing $profile array on the screen which holds the basic info about user
        //$_SESSION['facebook_profile'] = $userProfile;
                       
        $social['oauth_provider'] = 'facebook'; 
        $social['oauth_uid'] = $userProfile['id'];        
        $picture = 'http://graph.facebook.com/'.$userProfile['id'].'/picture';
        $social['picture']  = $picture;
        $social['link']  = $userProfile['link'];
        
        $user['lastname'] = $userProfile['last_name'];
        $user['firstname'] = $userProfile['first_name'];
        $user['email']  = $userProfile['email'];

        $email  = $userProfile['email'];

         $this->socialcheck($social, $user, $email);
         
    } else {
        // replace your website URL same as added in the developers.facebook.com/apps e.g. if you used http instead of https and you used non-www version or www version of your website then you must add the same here
        $loginUrl = $helper->getLoginUrl(SITEURL.FACEBOOK_REROUTE.'/'.$permissions);
        $login =  '<a href="' . $loginUrl . '">Log in with Facebook!</a>';
        $this->set('login',$login);
    }
}

now the function that updates our social users tables and users tables

this function will be used for our facebook, google, linkedin, twitter and all other one click social login systems

function socialcheck($social, $user, $email) {
	
	$this->loadModel('UserSocial');
	$options = array('conditions' => array('UserSocial.oauth_uid' => $social['oauth_uid']));
	$findsocialuser = $this->UserSocial->find('first',$options);
	
	if(!empty($findsocialuser)){
	
		$userdata['id']	=	$findsocialuser['UserSocial']['id'];
		$userdata['modified']	=	date("Y-m-d H:i:s");
		
		$this->UserSocial->save($userdata,false);
		$social_id = $findsocialuser['UserSocial']['id'];
	
	} else {
		
		$userdata = $social;	
		$userdata['created']	=	date("Y-m-d H:i:s");
		$userdata['modified']	=	date("Y-m-d H:i:s");
		
		$this->UserSocial->save($userdata,false);      

	}
    
		$this->loadModel('User');
		
		$options = array('conditions' => array('User.email' => $email));
		$finduser = $this->User->find('first',$options);
		
		if($social['oauth_provider'] == 'google') { $data['google_id'] = $social['oauth_uid']; }
		if($social['oauth_provider'] == 'facebook') { $data['facebook_id'] = $social['oauth_uid']; }
		if($social['oauth_provider'] == 'linkedin') { $data['linkedin_id'] = $social['oauth_uid']; }
    
	if(!empty($finduser)){
		
		$data['id']	=	$finduser['User']['id'];
		$data['modified']	=	date("Y-m-d H:i:s");
	
		$this->User->save($data,false);
		
	} else {
			
		$data  = $user;
		// setting data to the user data that will contain the first names email addresses ect
		
		$data['password']	=	AuthComponent::password($user['firstname']);
		// creating a password for the user in our database -->this can be emailed to the user
	
		$this->User->save($data, false);
	
	}
}

 

Published: 9th May 2017 by

Adverts